import axios from 'axios'

const service = axios.create({
    baseURL: '/api',
    timeout: 5000
})

// 请求拦截器 - 添加认证令牌
service.interceptors.request.use(config => {
    const token = localStorage.getItem('token') || sessionStorage.getItem('token')
    if (token) {
        config.headers.Authorization = `Bearer ${token}`
    }
    return config
})

// 响应拦截器 - 统一错误处理
service.interceptors.response.use(
    response => {
        if (response.status === 200) {
            return response.data
        }
        return Promise.reject(new Error('请求异常'))
    },
    error => {
        const status = error.response?.status
        const message = error.response?.data?.message || '服务异常'

        // 根据状态码处理不同业务场景
        switch (status) {
            case 401:
                window.location.href = '/login'
                break
            case 403:
                console.warn('权限不足')
                break
            case 500:
                console.error('服务器错误')
                break
        }

        return Promise.reject({ status, message })
    }
)

export const http = {
    get<T>(url: string, params?: object): Promise<T> {
        return service.get(url, { params })
    },
    post<T>(url: string, data?: object): Promise<T> {
        return service.post(url, data)
    },
    put<T>(url: string, data?: object): Promise<T> {
        return service.put(url, data)
    },
    delete<T>(url: string, params?: object): Promise<T> {
        return service.delete(url, { params })
    }
}